//
//  MapViewController.m
//  DongChiDaChiProject1
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "MapViewController.h"
#import "MoviePlayerViewController.h"
#import "HJCarouselViewLayout.h"
#import "CollectionViewCell.h"
#import "CollectModel.h"
#import "SecondViewController.h"
#import "UserManager.h"

@interface MapViewController ()<MoviePlayerViewControllerDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UIImageView *imageV;
@property (nonatomic, strong) MoviePlayerViewController *moviePlayerVC;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSArray *videoListArray;

@property (nonatomic, strong) NSMutableArray *dataArray;

//
@property (nonatomic, strong)NSString *str;// 保存 URL 播放地址

@end

@implementation MapViewController

static NSString *const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"推荐";
    self.view.backgroundColor = [UIColor colorWithHue:0.1 saturation:0.3 brightness:1 alpha:1];
     [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithHue:0.1 saturation:0.3 brightness:1 alpha:0.7]];
    
  
    

}

- (void)viewDidAppear:(BOOL)animated
{
    [self searchNet];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [self.collectionView removeFromSuperview];
    self.collectionView = nil;
}

#pragma mark - 添加网络检测
- (void)searchNet
{
    NSLog(@"wangluo = %@", [[UserManager shareUserManagerHandle] getNet]);
    
    if ([[[UserManager shareUserManagerHandle] getNet] isEqualToString:@"NO"]) {
        // 网络不通
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"警告" message:@"该软件只有在网络状态下才能使用" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertVC addAction:alertAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    } else {
        // block 回调
        __block MapViewController *mySelf = self;
        [self setUpDataWithBlock:^(NSMutableArray *array) {
            mySelf.dataArray = array;
            // [mySelf.collectionView reloadData];
            
            [mySelf addSubView];
        }];
    }
}

////////////////////////*******************实验区*************************////////////////
// 懒加载
- (MoviePlayerViewController *)moviePlayerVC
{
    if (!_moviePlayerVC) {
        _moviePlayerVC = [[MoviePlayerViewController alloc] init];
        _moviePlayerVC.delegate = self;
        //_moviePlayerVC.movieURL = [[NSBundle mainBundle] URLForResource:@"中英字幕 Taylor.Swift--Sparks Fly  现场版 标清.mp4" withExtension:nil];
        // 网上视频
        self.moviePlayerVC.movieURL = [NSURL URLWithString:self.str];
        
        // 截屏
        [_moviePlayerVC captureImageAtTime:5.0];
        
        
    }
    return _moviePlayerVC;
}

////////***********************实验区******************************
// 解析数据
- (void)setUpDataWithBlock:(void(^)(NSMutableArray *array))block
{

    

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:@"http://baobab.wandoujia.com/api/v1/videos?categoryName=%E5%BC%80%E8%83%83&udid=d74ecfa50ec94615a2c4483236c9cd58bfa62b44&vc=48&vn=1.5.1&deviceModel=SM-G9009W&first_channel=eyepetizer_PP_market&last_channel=eyepetizer_PP_market"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
        [request setHTTPMethod:@"GET"];
        
        // 7.0 新添加方法
        // 创建 config
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        // 根据 config 创建 session
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataDusk = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            //
            if (!data) {
                return;
            }
            self.dataArray = [NSMutableArray array];
            // 在这里请求数据
            NSDictionary *Dic3 = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            self.videoListArray = Dic3[@"videoList"];// 数组里是字典 进行遍历
            NSLog(@"6666666666==============0 = %ld", (unsigned long)self.videoListArray.count);
            for (NSDictionary *dic17 in self.videoListArray) {
                //创建 model
                CollectModel *model = [[CollectModel alloc] init];
                [model setValuesForKeysWithDictionary:dic17];
                // 保存到自己的数组中 但是要初始化数组
                [self.dataArray addObject:model];
                NSLog(@"6666%@", model);
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //block 回调
                block(self.dataArray);
            });
           

            
        }];
        [dataDusk resume];
        
    });
   
    //NSLog(@"66666666666==============1 = %ld", (unsigned long)self.videoListArray.count);
}

- (void)addSubView
{
    
    HJCarouselViewLayout *layOut = [[HJCarouselViewLayout alloc] initWithAnim:HJCarouselAnimLinear];
    layOut.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layOut.itemSize = CGSizeMake(250, 250);
    layOut.visibleCount = 100;
    self.collectionView  =[[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layOut];
    self.collectionView.backgroundColor = [[UIColor orangeColor]colorWithAlphaComponent:0.2];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    self.collectionView.delegate = self;
    self.collectionView.dataSource =self;
    [self.view addSubview:_collectionView];
    
}

// 单元格数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
  //  NSLog(@"------------------- 0000 =%ld", (unsigned long)self.videoListArray.count);
    return self.dataArray.count;
    
}
// 单元格设置
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
   
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    if (self.dataArray.count > indexPath.row) {
        CollectModel *model = self.dataArray[indexPath.row];
        [cell.viewCell sd_setImageWithURL:[NSURL URLWithString:model.coverForFeed] placeholderImage:[UIImage imageNamed:@"placehoder.jpg"]];
    }
  
   // cell.viewCell.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.coverForFeed]]];
    
    
    return cell;
}

// collectionView 的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectModel *model = self.dataArray[indexPath.row];


    self.str = model.playUrl;

    [self presentViewController:self.moviePlayerVC animated:YES completion:nil];

    self.moviePlayerVC = nil;
    
}


// 播放器设置
// 结束的时候回到主页面
- (void)moviePlayerDidFinished
{
    // 谁申请谁释放
    // dismissViewControllerAnimated将当前视图控制器的模态窗口关闭
    [self dismissViewControllerAnimated:YES completion:nil];
}
// 截屏

- (void)moviePlayerDidCaptureWithImage:(UIImage *)image
{
//    self.imageV = [[UIImageView alloc] initWithFrame:CGRectMake(10, 250, 355, 200)];
//    self.imageV.image = image;
//    [self.view addSubview:_imageV];
    
    
}





    








@end
